package com.qf.controller;

import com.alibaba.druid.util.StringUtils;
import com.qf.captcha.CaptchaCodeManager;
import com.qf.pojo.DtsAdmin;
import com.qf.service.PermissionService;
import com.qf.service.RoleService;
import com.qf.util.Base64;
import com.qf.util.UUID;
import com.qf.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayOutputStream;
import java.util.*;

@RestController
@RequestMapping("/auth")
@CrossOrigin("*")
@Api(value = "权限相关接口, 登录, 注销, 验证码")
public class AuthController {

    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private ApplicationContext context;
    private HashMap<String,String> systemPerMap=null;
    private  static final Logger logger= LoggerFactory.getLogger(AuthController.class);

    @RequestMapping("/captchaImage")
    @ApiOperation(value = "获取登录验证码图片")
    public Object findcode() throws Exception{
        String codeStr = VerifyCodeUtils.generateVerifyCode(4);
        String uuid = UUID.randomUUID().toString(true);
        boolean add = CaptchaCodeManager.addToCache(uuid, codeStr, 10);
        if (!add){
            logger.error("生成验证码出错:{}", AdminResponseCode.AUTH_CAPTCHA_FREQUENCY.desc());
            return AdminResponseUtil.fail(AdminResponseCode.AUTH_CAPTCHA_FREQUENCY);
        }
        int w=100;
        int h=40;
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        VerifyCodeUtils.outputImage(w,h,outputStream,codeStr);

        HashMap<String, Object> date = new HashMap<>();
        date.put("img",Base64.encode(outputStream.toByteArray()));
        date.put("uuid",uuid);

        return ResponseUtil.ok(date);
    }
    @RequestMapping("/login")
    public Object login(@RequestBody String body){
        String code= JacksonUtil.parseString(body, "code");
        String username = JacksonUtil.parseString(body, "username");
        String password = JacksonUtil.parseString(body, "password");
        String uuid = JacksonUtil.parseString(body, "uuid");

        if (StringUtils.isEmpty(code)||StringUtils.isEmpty(username)||StringUtils.isEmpty(password)||StringUtils.isEmpty(uuid)){
            return ResponseUtil.badArgument();
        }
        String cachedCaptcha = CaptchaCodeManager.getCachedCaptcha(uuid);
        if (cachedCaptcha==null){
            return AdminResponseUtil.fail(AdminResponseCode.AUTH_CAPTCHA_EXPIRED);
        }
        if (!code.equalsIgnoreCase(cachedCaptcha)){
            return AdminResponseUtil.fail(AdminResponseCode.AUTH_CAPTCHA_ERROR);
        }
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
            return AdminResponseUtil.fail(AdminResponseCode.ADMIN_INVALID_ACCOUNT_OR_PASSWORD);
        }catch (AuthenticationException e) {
            return AdminResponseUtil.fail(AdminResponseCode.ADMIN_INVALID_AUTH);
        }
        return ResponseUtil.ok(subject.getSession().getId());
    }
    @RequestMapping("/info")
    public Object info(){
        Subject subject = SecurityUtils.getSubject();
        DtsAdmin admin =(DtsAdmin) subject.getPrincipal();
        Map<String, Object> data = new HashMap<>();
        data.put("name",admin.getUsername());
        data.put("avatar",admin.getAvatar());
        Integer[] ids = admin.getRoleIds();
        Set<String> roles = roleService.queryByIds(ids);
        data.put("roles",roles);
        Set<String> permisson = permissionService.queryPermissonByRoleIds(ids);
        data.put("perms",toApi(permisson));
        return ResponseUtil.ok(data);
    }
    @RequestMapping("/logout")
    public Object logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return ResponseUtil.ok();
    }
    public Collection<String> toApi(Set<String> permisson){
        if (systemPerMap==null||systemPerMap.size()==0){
            systemPerMap=new HashMap<>();
            String basicPackage="com.qf";
            List<Permission> permissionList = PermissionUtil.listPermission(context, basicPackage);
            for (Permission permission : permissionList) {
                String[] per = permission.getRequiresPermissions().value();
                String api = permission.getApi();
                systemPerMap.put(per[0],api);
            }
        }
        Collection<String> apis = new HashSet<>();
        for (String per : permisson) {
            String api = systemPerMap.get(per);
            apis.add(api);
            if (per.equals("*")){
                apis.clear();
                apis.add("*");
                return apis;
            }
        }
        return apis;
    }
}
